IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[cms_sp_PageDelete]') AND type in (N'P', N'PC'))
	DROP PROCEDURE [dbo].[cms_sp_PageDelete]
GO
create procedure [dbo].[cms_sp_PageDelete]
(
@Id int,
@PageTypeParameter nvarchar(150)
)
as
declare @PageNodeId hierarchyid
declare @PublicPageId int
declare @SiteId int
declare @SiteGroupId int
select
	@PageNodeId = PageNodeId,
	@PublicPageId = PublicPageId,
	@SiteId = SiteId,
	@SiteGroupId = SiteGroupId
from dbo.Pages
where PageId = @Id

delete from dbo.EntityRevisions
where EntityTypeParameter = @PageTypeParameter AND
	PublicEntityId IN (
	select distinct PublicPageId 
	 from dbo.Pages
	 where PageNodeId.IsDescendantOf(@PageNodeId) = 1 AND
	    ((Pages.SiteGroupId is null and Pages.SiteId is null) or 
		(Pages.SiteGroupId = @SiteGroupId and Pages.SiteId is null) or
		(Pages.SiteGroupId = @SiteGroupId and Pages.SiteId = @SiteId))
    ) 	  

delete from dbo.Pages
where PageNodeId.IsDescendantOf(@PageNodeId) = 1 AND
    ((Pages.SiteGroupId is null and Pages.SiteId is null) or 
	(Pages.SiteGroupId = @SiteGroupId and Pages.SiteId is null) or
	(Pages.SiteGroupId = @SiteGroupId and Pages.SiteId = @SiteId))

GO

